import { createRequire } from 'module'
import axios from 'axios';
const require = createRequire(import.meta.url)
const express = require('express')
const noticeRouter = express.Router();
import { mysqlObj } from '../../utils/mysql.js'
/**
 * 后台得到通告列表
 */
noticeRouter.get("/getNoticeList", function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((connct) => {
        connct.query("select * from notices", function (error, results, fields) {
            if (error) throw error;
            let json = {};
            json.list = results;
            res.write(JSON.stringify(json));
            res.end();
        })
    })
})
/**
 * 后台根据notice_id查通告
 */
noticeRouter.get("/searchNotice", function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
    let notice_id = req.query.notice_id;
    mysqlObj.create().then((connct) => {
        connct.query(`select * from notices where notice_id=${notice_id}`, function (error, results, fields) {
            if (error) throw error;
            let json = {};
            json.list = results;
            res.write(JSON.stringify(json));
            res.end();
        })
    })
})
/**
 * 更新notice通告
 */
noticeRouter.get("/updateNotice", function (req, res) {
    res.writeHead(200, { "Content-type": "text/html;charset=utf-8" })
    console.log(req.query, 'query')
    let notice_id = req.query.notice_id;
    let content = req.query.content;
    Boolean(notice_id) == false ? notice_id = 0 : ""
    console.log(notice_id, content)
    mysqlObj.create().then((connct) => {
        connct.query(`update notices set content=${content} where notice_id='${notice_id}'`, function (error, results, fields) {
            if (error) throw error;
            res.write("200");
            res.end();
        })
    })
})
/**
 * 删除单个通告
 */
noticeRouter.get("/deleteNotice", function(req, res) {
    res.writeHead(200, {"Content-type": "text/html;charset=utf-8"})
    let notice_id = req.query.notice_id;
    mysqlObj.create().then((connct) => {
        connct.query(`delete from notices where notice_id=${notice_id}`, function(error, results, fields) {
            if(error) throw error;
            res.write("200");
            res.end();
        })
    })
})
/**
 * 前台得到单个通告
 */
noticeRouter.get("/getNotice", function (req, res) {
    res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
    mysqlObj.create().then((connct) => {
        connct.query("select * from notices", function (error, results, fields) {
            if (error) throw error;
            let index = Math.floor(Math.random() * (results.length));
            let value = results[index];
            res.write(JSON.stringify(value));
            res.end();
        })
    })
})
export const notice = noticeRouter;